package com.house365.im.client.util;

import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;
/**
 *@Author Rick.Ping
 *@Date 2014-08-14
 *@Comment
 **/
public  class SoundUtil {
	private static final String LOGTAG = LogUtil.makeLogTag(SoundUtil.class);
	static final private double EMA_FILTER = 0.6;

	private MediaRecorder mRecorder = null;
	private double mEMA = 0.0;

	/**
	 * start record
	 * @param path
	 */
	public void start(String path) {
		if (!Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			return;
		}
		if (mRecorder == null) {
			mRecorder = new MediaRecorder();
			mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
			mRecorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
			mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
			mRecorder.setOutputFile(path);
			try {
				mRecorder.prepare();
				mRecorder.start();
				mEMA = 0.0;
			} catch (Exception e) {
				Log.e(LOGTAG, "start Exception");
			}

		}
	}
	
	public void stop() {
		try {
			if (mRecorder != null) {
				mRecorder.stop();
				mRecorder.release();
				mRecorder = null;
			}
		} catch (Exception e) {
			Log.e(LOGTAG, "stop Exception");
		}
	}


	public double getAmplitude() {
		if (mRecorder != null)
			return (mRecorder.getMaxAmplitude() / 2700.0);
		else
			return 0;

	}

	public double getAmplitudeEMA() {
		double amp = getAmplitude();
		mEMA = EMA_FILTER * amp + (1.0 - EMA_FILTER) * mEMA;
		return mEMA;
	}	
}
